`
https://leetcode.cn/problems/bag-of-tokens/
`

/**
 * @param {number[]} tokens
 * @param {number} power
 * @return {number}
 */
var bagOfTokensScore = function (tokens, power) {
  tokens.sort((a, b) => a - b)
  let score = 0
  let left = 0, right = tokens.length - 1
  let res = 0

  while (left <= right && (power >= tokens[left] || score > 0)) {
    // 拿左边的加分，拿右边的加power
    while (left <= right && power >= tokens[left]) {
      power -= tokens[left++]
      score++
    }
    // 令牌可以用或不用，保存最大的结果
    res = Math.max(res, score)
    if (left <= right && score > 0) {
      power += tokens[right--]
      score--
    }
  }

  return res
};